package share.security.auth;

import java.io.FileNotFoundException;

import javax.servlet.http.HttpSession;

import org.eu.base.security.Encrypt;
import org.eu.config.Config;
import org.eu.config.ConfigFile;
import org.eu.config.ConfigManager;
import org.eu.config.ConfigMissingException;

import share.storage.io.File;

public class BasicAuth implements Authenticator {
	
	private HttpSession session;
	
	BasicAuth(HttpSession session){
		this.session=session;
	}
	
	public User login(String username, String password) {
		String file=ConfigManager.getEnviroment("WebRoot")+"WEB-INF/user.list";
		ConfigFile cf=ConfigManager.getConfigFile(file);
		if(cf==null)
			try {
				cf=ConfigManager.loadConfigFile(file);
			} catch (FileNotFoundException e1) {
				return null;
			}
		Config config=cf.getConfig("user");
		try {
			if(config.getValue(username).equals(Encrypt.md5(password))){
				User user=new User(username);
				session.setAttribute("BasicAuth.User", user);
				return user;
			}
		} catch (ConfigMissingException e) {
			return null;
		}
		return null;
	}
	
	public User hasLogin() {
		User user=(User) session.getAttribute("BasicAuth.User");
		return user;
	}

	public User isAdmin() {
		return hasLogin();
	}

	public User canUpload() {
		return hasLogin();
	}

	public User canDownload(File file) {
		return hasLogin();
	}

	public void logout() {
		session.removeAttribute("BasicAuth.User");
	}

}
